package com.coder.util;



import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coder.bean.WebResult;
import com.coder.common.util.MD5Util;



/**
 * Api校验
 * 
 * @author lzm
 *
 */
public class ApiValidate {

	private static final Logger log = LoggerFactory.getLogger(ApiValidate.class);

	/**
	 * 签名验证
	 * @param request
	 * @param app
	 * @param sign
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static WebResult validateSign(HttpServletRequest request, String sign,String appsecret) {
		Map<String, String> param = RequestUtils.getSignMap(request);
		String validateSign = createSign(param, appsecret);
		if (!sign.equals(validateSign)) {
			return WebResult.getErrorResult(WebResult.Code.SIGN_ERROR);
		}
		return WebResult.getSuccessResult();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String createSign(Map<String, String> param, String key) {
		// 签名步骤一：按字典排序参数
		List list = new ArrayList(param.keySet());
		Object[] ary = list.toArray();
		Arrays.sort(ary);
		list = Arrays.asList(ary);
		String str = "";
		for (int i = 0; i < list.size(); i++) {
			String value = param.get(list.get(i) + "");
			if(!"[object Undefined]".equals(value)&&!"undefined".equals(value)&&!"null".equals(value) && value!=null && !"".equals(value.trim())){
				str += list.get(i) + "=" + param.get(list.get(i) + "") + "&";
			}
		}
		// 签名步骤二：加上key
		str += "key=" + key;
		// 步骤三：加密并小写
		str = MD5Util.md5(str).toLowerCase();
		return str;
	}
	
	/**
	 * 加密工具类
	 * MD5加密
	 * HMAC加密
	 *
	 */
	static class CryptUtils {
	    private static final String KEY_MD5 = "MD5";
	    // 全局数组
	    private static final String[] strDigits = { "0", "1", "2", "3", "4", "5",
	            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

	    // 返回形式为数字跟字符串
	    private static String byteToArrayString(byte bByte) {
	        int iRet = bByte;
	        if (iRet < 0) {
	            iRet += 256;
	        }
	        int iD1 = iRet / 16;
	        int iD2 = iRet % 16;
	        return strDigits[iD1] + strDigits[iD2];
	    }

	    // 转换字节数组为16进制字串
	    private static String byteToString(byte[] bByte) {
	        StringBuffer sBuffer = new StringBuffer();
	        for (int i = 0; i < bByte.length; i++) {
	            sBuffer.append(byteToArrayString(bByte[i]));
	        }
	        return sBuffer.toString();
	    }
	    /**
	     * MD5加密
	     * @param strObj
	     * @return
	     * @throws Exception
	     */
	    public static String getMD5Code(String strObj) throws Exception{
	        MessageDigest md = MessageDigest.getInstance(KEY_MD5);
	        // md.digest() 该函数返回值为存放哈希值结果的byte数组
	        return byteToString(md.digest(strObj.getBytes("utf-8")));
	    }

	}
	
	public static void main(String[] args) {
		String str = "appId=80000003&birthdate=2017-05-22&gender=1&integral=1&name=测试&note=1&phone=19099989990&token=06fd8b8504ec41f89412309ece33a118&key=5ed4261784a40667";
		try {
			str = CryptUtils.getMD5Code(str).toLowerCase();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(str);
	}

}
